const mongoose = require('mongoose')
const glob = require('glob')
const {resolve} = require('path')
//连接本地数据库
const db = "mongodb://localhost:27017/aicode"
//mongoose.Promise = global.Promise
//一次性引入所有的Schema文件
exports.initSchemas = () =>{
    glob.sync(resolve(__dirname,'./schema/','**/*.js')).forEach(require)
}
exports.connect = ()=>{
    //连接数据库
    mongoose.connect(db, { useNewUrlParser: true })
    //最大连接数
    let maxConnectTimes = 0
    return new Promise((resolve,reject)=>{
        //增加数据库连接的时间监听
        mongoose.connection.on('disconnected',()=>{
            console.log('***********数据库断开***********')
            //进行重新连接
           // mongoose.connect(db)
           if(maxConnectTimes<3){
               maxConnectTimes++
              mongoose.connect(db, { useNewUrlParser: true })
           }else{
               reject()
               throw new Error('亲亲，数据库出现问题啦')
           }
        })

        //数据库出现错误的时候
        mongoose.connection.on('error',err=>{
            console.log('***********数据库错误***********')
            //mongoose.connect(db)
            if(maxConnectTimes<3){
                maxConnectTimes++
                mongoose.connect(db, { useNewUrlParser: true })
            }else{
                reject(err)
                throw new Error('亲亲，数据库出现问题啦')
            }
        })

        //链接打开的时候
        mongoose.connection.once('open',()=>{
            console.log('MongoDB Connected successfully!')
            resolve()
        })
    })
}